from jili.data.db import getdb_client
from copy import deepcopy
import pandas as pd
def get_objs_index_sws(key="index_code",nodeal=[]):
    cuname="index_calssify_sws_level_rq"
    db=getdb_client(dbname="stock")
    objs=db[cuname].distinct(key)
    for i in nodeal:
        if i in objs:
            objs.remove(i)
    return objs
def get_objs_index(cuname,ip="127.0.0.1",key="index_code",nodeal=[],detail_cu=None):
    db=getdb_client(ip=ip,dbname="stock")
    objs=db[cuname].distinct(key)
    objs0=db[cuname].distinct(key)
    nodeal0=deepcopy(nodeal)
    objs1=[]
    if detail_cu:
        for i in db[detail_cu].find({}):
            s=i["code"].split(".")
            if len(s)==2:
                obj, mk = s
                if mk not in ["SH", "SZ"]:
                    index_code = i["index_code"]
                    if index_code not in nodeal0:
                        nodeal0.append(index_code)
                else:
                    index_code = i["index_code"]
                    if index_code not in objs1 and index_code in objs0:
                        objs1.append(index_code)
            # else:
            #     print(s)
    for i in nodeal0:
        if i in objs:
            objs.remove(i)
    return objs
def get_objs_index2(cuname,ip="127.0.0.1",key="index_code",nodeal=[],detail_cu=None):
    db=getdb_client(ip=ip,dbname="stock")
    objs=db[cuname].distinct(key)
    objs0=db[cuname].distinct(key)
    nodeal0=deepcopy(nodeal)
    rst={}
    # objs1 = []
    # rst1={}
    # for i in db[cuname].find():
    #     rst1[i["ts_code"]]=i["name"]
    if detail_cu:
        for i in db[detail_cu].find({}):
            s=i["code"].split(".")
            if len(s)==2:
                obj, mk = s
                if mk not in ["SH", "SZ","BJ"]:
                    index_code = i["index_code"]
                    if index_code not in nodeal0:
                        nodeal0.append(index_code)
                else:
                    index_code = i["index_code"]
                    if index_code in objs0:
                        if index_code not in rst.keys():
                            rst[index_code]=[]
                        rst[index_code].append(mk)
    for i in nodeal0:
        if i in objs:
            objs.remove(i)
    for i ,v in rst.items():
        r=v.count("BJ")/len(v)
        if r>=0.3:
            objs.remove(i)
            # print(i)
    # print("obj1---obj")
    # for i in objs1:
    #     if i not in objs:
    #         print(i,rst1[i])
    # names=[]
    # a1 = pd.read_excel(r"G:/price/ths_name软件.xlsx")
    # names=a1["name"].to_list()
    # print("ob---软件")
    # for i in objs:
    #     n=rst1[i]
    #     if n not in names:
    #         print(i, n)
    return objs

if __name__=="__main__":
    objs=get_objs_index2(cuname="index_calssify_ths_concept_level",ip="127.0.0.1",key="index_code",nodeal=["883300.TI", "883301.TI", "883302.TI", "883303.TI", "883304.TI"],detail_cu="index_calssify_ths_concept_detail")